package com.yys.gulimall.order.config;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author zq
 * @version 1.0
 * @date 2021/4/2 21:13
 */
@Configuration
public class MyRabbitConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    @PostConstruct
    public void initRabbitTemplate() {
        /*
         * 定制RabbitTemplate
         * 要消息抵达broker ack就为true
         * @param correlationData 消息唯一关联
         * @param ack 消息是否成功收到
         * @param cause 失败的原因
         *
         * PS:
         *  correlationData: CorrelationData [id=448ed943-6e75-499b-a1c8-86a0251c9350]
         *  ack: true
         *  cause: null
         */
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("confirm...");
            System.out.println(correlationData);
            System.out.println(ack);
            System.out.println(cause);
        });

        /*
          只要消息没有投递给指定队列就会触发这个回调
          @param message 投递失败的消息详细信息
         * @param replyCode 回复的状态码
         * @param replyText 回复的文本内容
         * @param exchange 发送的交换机
         * @param routingKey 发送的routingKey
         *
         * PS:
         *  message: (Body:'{"hello":"world"}' MessageProperties [headers={__ContentTypeId__=java.lang.Object, __KeyTypeId__=java.lang.Object, __TypeId__=java.util.HashMap}, contentType=application/json, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, deliveryTag=0])
         *  replyCode: 312
         *  replyText: NO_ROUTE
         *  exchange: hello.java.exchange
         *  routingKey: ERROR_ROUTING_KEY
         */
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println("FailMessage...");
            System.out.println(message);
            System.out.println(replyCode);
            System.out.println(replyText);
            System.out.println(exchange);
            System.out.println(routingKey);
        });
    }

}
